import React from 'react';
import { Link, withRouter } from 'react-router';
import { connect } from 'react-redux';
import Pagination from 'rc-pagination';
import Dialog from 'rc-dialog';
import testCategoryAction from '../../actions/testCategoryAction.js';
import Input from '../base/Input.js';
import Widget from '../mui/Widget.js';
import SearchInput from '../mui/searchInput.js';

const TestCategoryList = React.createClass({
  edit(item) {
    if (this.props.edit) {
      this.props.edit(item, 'edit');
    }
  },
  showPushLog(item) {
    if (this.props.showPushLog) {
      this.props.showPushLog(item);
    }
  },
  render() {
    return (
      <tbody>
      {
        this.props.List.map((item, index) =>
          <tr key={index}>
            <td>{item.created}</td>
            <td>{item.clsno}</td>
            <td>{item.name}</td>
            <td className="text-left"><pre className="pre-remark">{item.remark}</pre></td>
            <td className="device-manage">
              <span className="pull-left">共{item.devices ? item.devices : '0'}个</span>
              <Link to={`/testCategory/childrenDevice/${item._id}`} className="pull-right">管理</Link>
            </td>
            <td><a onClick={this.edit.bind(this, item)}>编辑</a></td>
            <td>
              {
                item.devices ?
                  <Link to={`/testCategory/pushCategory/${item._id}`}>推送至测试类</Link>
                :
                  <span className="disable-message">推送至测试类</span>
              }
            </td>
            <td>
              {
                item.pushed ?
                  <a onClick={ this.showPushLog.bind(this, item) }>查看</a>
                :
                  <span className="disable-message">无记录</span>
              }
            </td>
          </tr>
        )
      }
      </tbody>
    );
  }
});

const TestCategory = withRouter(
  React.createClass({
    getInitialState() {
      return {
        visible: false,
        destroyOnClose: false,
        pushLogPage: false,
        buttonState: false,
        pushItemLogId: '',
        pageList: [],
        formData:{
          clsno:'',
          name:'',
          remark: '',
          id: ''
        }
      };
    },
    componentWillMount() {
      const data = {
        keyword: '',
        page: 1,
        page_size: 15
      };     
      const { fetchTestCategoryList } = this.props;
      fetchTestCategoryList(data);
    },
    componentWillReceiveProps(nextProps) {
      this.setState({ pageList: nextProps.CategoryList.data });
      if (nextProps.saveMsg.code === 200) {
        this.setState({ visible: false });
      }
    },
    onClose() {
      this.setState({
        visible: false,
      });
    },
    handleChange(targetData) {
      // 序列化表单
      // ============
      const fData = this.state.formData;
      fData[targetData.name] = targetData.value;
      this.setState({
        formData: fData,
      });
      // 如果有为空情况，不能点击保存按钮
      // ==============================
      if (!fData.name) {
        this.setState({ buttonState: false });
      } else {
        this.setState({ buttonState: true });
      }
    },
    handleCheckSpace(targetData) {
      // 如果有为空情况，不能点击保存按钮
      // ==============================
      const fData = this.state.formData;
      for (const key in fData) {
        if (key !== 'size') {
          fData[key] = fData[key].trim();
        }
        if (!fData[key] && key !== 'remark' && key !== 'id') {
          this.setState({ buttonState: false });
          break;
        } else {
          this.setState({ buttonState: true });
        }
      }
    },
    newTestCategory() {
      const { saveTestCategory, editTestCategory } = this.props;
      if (!this.state.formData.id) {
        saveTestCategory(this.state.formData, this.props.router);
      } else {
        editTestCategory(this.state.formData, this.props.router);
      }
    },
    editCategory(item, flag) {
      this.editFlag = flag;
      this.setState(
        {
          visible: true,
          formData:
          {
            clsno: item.clsno,
            name: item.name,
            remark: item.remark,
            id: item._id
          }
        });
    },
    newDialog() {
      this.setState({ visible: true, formData:{ name:'', remark:'', id: '' } });
    },
    showPushLog(item) {
      this.setState({ pushLogPage: true, pushItemLogId:  item._id, categoryName: item.name });
      const { fetchPushCategoryLog } = this.props;
      this.itemId = item._id;
      fetchPushCategoryLog({ id: item._id, page_size: 30 });
    },
    cancelPushLog() {
      this.setState({ pushLogPage: false });
    },
    // 关闭编辑弹出框
    // ==============
    cancelReturn() {
      this.setState({
        visible: false,
      });
    },
    search(target) {
      this.searchValue = target.value;
      const data = {
        keyword: target.value,
        page_size: 15
      };
      const { fetchTestCategoryList } = this.props;
      fetchTestCategoryList(data);
    },
    searchPushLog(target) {
      this.searchPushLogValue = target.value;
      const data = {
        keyword: target.value,
        id: this.state.pushItemLogId
      };
      const { fetchPushCategoryLog } = this.props;
      fetchPushCategoryLog(data);
    },
    paginationPushLog(pageNumber) {
      const data = {
        page: pageNumber,
        keyword: this.searchPushLogValue,
        page_size: 30,
        id: this.itemId
      };
      const { fetchPushCategoryLog } = this.props;
      fetchPushCategoryLog(data);
    },
    pagination(pageNumber) {
      const data = {
        page: pageNumber,
        keyword: this.searchValue,
        page_size: 15
      };
      const { fetchTestCategoryList } = this.props;
      fetchTestCategoryList(data);
    },
    render() {
      const pages = this.props.CategoryList.pages * 10 || 0;
      const { pushCategoryLog, CategoryList } = this.props;
      const { categoryName } = this.state;
      let dialog;
      let pushLogPageDialog;
      const button = <button className="btn btn-primary w120 mr40 ml20" key="close" onClick={this.newTestCategory}>保存</button>;
      const disableButton = <button className="btn btn-disable w120 mr40 ml20" key="close" disabled="disabled">保存</button>;
      if (this.state.visible || !this.state.destroyOnClose) {
        dialog = (
          <Dialog
            prefixCls={'form-dialog'} visible={this.state.visible} animation="slide-fade" maskAnimation="fade"
            // onClose={this.cancelReturn}
            style={{ width: 480 }}
            // bodyStyle={{ height: 390 }}
            // title={<div>第二个弹框</div>}
            footer={
            [this.state.buttonState ? button : disableButton,
              <button type="button" className="btn btn-cancel w120" key="save" onClick={this.cancelReturn} >
                取消
              </button>,
            ]
            }
          >
            <div>
              <p className="dialog-title">{this.editFlag ? '编辑测试类' : '添加测试类'}</p>
              <form className="f-group-290">
                <div className="form-group">
                  {this.state.formData.clsno ? <label className="control-label" htmlFor="name">类编号</label> : ''}
                  {
                    this.state.formData.clsno ?
                      <div className="input-group">
                        <p className="init-message">{this.state.formData.clsno}</p>
                      </div>
                    :
                    ''
                  }
                  <label className="control-label" htmlFor="name">类名称</label>
                  <div className="input-group">
                    <Input
                      data-target="name"
                      type="text"
                      onChange={this.handleChange}
                      value={this.state.formData.name}
                      placeholder="(必填)"
                      maxLength={128}
                      onBlur={this.handleCheckSpace}
                    />
                  </div>
                   {// saveErrorMsg.name === 'finger' ? <span className="text-danger">指纹重复，请重新输入</span> : ''
                 }
                </div>
                <div className="form-group">
                  <label className="control-label" htmlFor="remark">类描述</label>
                  <div className="input-group placeholder-normal">
                    <Input
                      data-target="remark"
                      type="textarea"
                      onChange={this.handleChange}
                      value={this.state.formData.remark}
                      rows={'5'}
                      placeholder="(选填)"
                      onBlur={this.handleCheckSpace}
                    />
                  </div>
                </div>
              </form>
            </div>
          </Dialog>
        );
      }
      // 推送记录弹出框
      // ===============
      if (this.state.pushLogPage) {
        pushLogPageDialog = (
          <Dialog
            prefixCls={'push-log-dialog'} visible={this.state.pushLogPage} animation="slide-fade" maskAnimation="fade"
            // onClose={this.cancelPushLog}
            style={{ width: 800 }}
            // bodyStyle={{ height: 540 }}
            // title={<div>第二个弹框</div>}
            // footer={
            // [<button type="button" className="btn btn-cancel w120" key="save" onClick={this.cancelPushLog} >
            //     取消
            // </button>,
            // ]
            // }
          >
            <div className="test-category-result">
              <Widget widgetName={categoryName} widgetHeader={'—推送记录'} closeLogo={this.cancelPushLog} />
              <div className="search">
                <SearchInput placeholder={"推送命名"} onSearch={this.searchPushLog} />
              </div>
              <div className="content-table">
                <table className="table table-hover">
                  <thead>
                    <tr>
                      <th className="w170">推送时间</th>
                      <th>推送命名</th>
                      <th>操作账号</th>
                    </tr>
                  </thead>
                  <tbody>
                  {
                    pushCategoryLog.data && pushCategoryLog.data.map((item, index) => {
                      return (
                        <tr key={index}>
                          <td>{item.created}</td>
                          <td>{item.name}</td>
                          <td>{item.username}</td>
                        </tr>
                      );
                    })
                  }
                  </tbody>
                </table>
              </div>
              <div className="pagination-block">
                <Pagination
                  className="ant-pagination"
                  current={pushCategoryLog.page}
                  defaultCurrent={1}
                  total={pushCategoryLog.pages ? pushCategoryLog.pages * 10 : 0}
                  onChange={this.paginationPushLog}
                />
              </div>
            </div>
          </Dialog>
        );
      }
      return (
        <div>
          <Widget widgetHeader={'测试类列表'} />
          <div className="widget-body">
            <div className="mw400">
              <button onClick={this.newDialog} className="btn btn-primary w160">添加测试类</button>
              <div className="pull-right">
                <SearchInput placeholder={"类编号、类名称"} onSearch={this.search} />
              </div>
            </div>
            <table className="table table-hover table-40">
              <thead>
                <tr>
                  <th className="m-w160">创建时间</th>
                  <th className="m-w115">类编号</th>
                  <th className="m-w150">类名称</th>
                  <th className="m-w210">类描述</th>
                  <th className="m-w150">子设备</th>
                  <th className="m-w85">类操作</th>
                  <th className="m-w100">推送</th>
                  <th className="m-w100">推送记录</th>
                </tr>
              </thead>
              <TestCategoryList List={this.state.pageList} edit={this.editCategory} showPushLog={this.showPushLog} />
            </table>
            <div className="mt50 mb100">
              <Pagination className="ant-pagination" defaultCurrent={1} current={CategoryList.page} total={pages} onChange={this.pagination} />
            </div>
          </div>
          {dialog}
          {pushLogPageDialog}
        </div>
      );
    }
  })
);

const mapStateToProps = function (state) {
  return {
    CategoryList: state.testCategory.testCategoryList,
    saveMsg: state.testCategory.saveMsg,
    pushCategoryLog: state.testCategory.pushCategoryLog
  };
};

module.exports = connect(mapStateToProps, testCategoryAction)(TestCategory);
// export default TestCategoryList;
